<?php
/**
 * Created by Sublime Text.
 * User: zhouyoupeng
 * Date: 2018/09/04
 * Time: 下午19:21
 */

namespace App\Helper;

use App\Models\Mzy\MzyDoctorSchedule;
use App\Models\Mzy\MzyStatVisitStation;
use App\Models\Mzy\MzyStation;

class StatVisitHelper
{
    // 社区-统计数据处理
    public static function statVisitStation()
    {
        // $testNum = 1; // 功能测试用
        // echo '<pre>';

        // 循环的对所有数据进行处理 ====================================================== start
        // 查找已经处理的统计数据
        $updatedAt = '';
        $oneStatVisitStation = MzyStatVisitStation::orderBy('updated_at','DESC')->first();
        if ($oneStatVisitStation)
        {
            $updatedTime = strtotime($oneStatVisitStation->updated_at);
            $updatedDate = date('Y-m', $updatedTime);
            $updatedDate = $updatedDate.'-01';
            $updatedDate = date('Y-m', strtotime($updatedDate) - 3600*24*2);
            $updatedDate = $updatedDate.'-12';  // 这个日期可以有效避免跨越周
            $updatedWeek = date('w', strtotime($updatedDate));
            $weekArr     = [7,1,2,3,4,5,6];
            $updatedAt = date('Y-m-d H:i:s',strtotime($updatedDate) - 3600*24*($weekArr[$updatedWeek]-1));
        }
        // 源数据表doctor_schedule里最初第一个月(程序统计中第一个出勤安排开始时间作为开始时间)x月的考勤数据从x-1月26日 到 x月25日
        if ($updatedAt)
        {
            $firstData  = MzyDoctorSchedule::where('updated_at','>=',$updatedAt)->orderBy('work_date','ASC')->first();
        }
        else
        {
            $firstData  = MzyDoctorSchedule::orderBy('work_date','ASC')->first();
        }
        if ($firstData)
        {
            $firstData = $firstData->toArray();
        }
        else
        {
            return false;
        }
        $firstTime  = strtotime($firstData['work_date']);    // 开始的时间戳
        $firstDay   = Date('d', $firstTime);
        $firstMonth = Date('m', $firstTime);
        $firstWeek  = Date('w', $firstTime);

        $weekArr    = [7,1,2,3,4,5,6];  // 按中国方式的星期（从星期一到星期日）
        $nowTime    = time();           // 当前时刻
        $nowDate    = DateHelper::now();
        $weekIndex  = 1;

        $whileNum = 0;  // 每次循环，增加1周
        while (($firstTime + 86400*(7 - $weekArr[$firstWeek] + 7*$whileNum)) < $nowTime)
        {
            // 星期数据处理
            $weekStartDate  = date('Y-m-d', $firstTime + 86400*(1 - $weekArr[$firstWeek] + 7*$whileNum));
            $weekStartDay   = date('d', $firstTime + 86400*(1 - $weekArr[$firstWeek] + 7*$whileNum));
            $weekEndDate    = date('Y-m-d', $firstTime + 86400*(7 - $weekArr[$firstWeek] + 7*$whileNum));
            $weekEndDay     = date('d', $firstTime + 86400*(7 - $weekArr[$firstWeek] + 7*$whileNum));

                // echo $testNum;
                // echo '<br>';
                // echo $weekStartDate;
                // echo '<br>';
                // echo $weekEndDate;
                // echo '<br>';

            // 统计的月份数据
            $monthEndDate   = date('Y-m', strtotime($weekStartDate));
            $monthEndDate   = $monthEndDate.'-25';
            $visitMonth     = $monthEndDate;        // x年x月，25日只是为了数据表保存visit_month
            $nextVisitMonth = date('Y-m', strtotime($monthEndDate) + 86400*7);
            $nextVisitMonth = $nextVisitMonth.'-25';// x+1月，25日只是为了数据表保存visit_month

            // 判断是否需要添加或者更新统计表
            $statVisitStatDate = DateHelper::now(); // 统计表里这一周“原始数据更新日期”最小的数据的“原始数据更新日期”
            $scheduleUpdatedAt = '';                // 新统计里这一周的数据中的“更新时间”
            $statVisitStationData = self::getStatVisitStationData($weekStartDate, $weekEndDate);
            $whatToDo = 'update';
            if ($statVisitStationData)
            {
                foreach ($statVisitStationData as $v)
                {
                    if ($statVisitStatDate > $v['schedule_updated_at'])
                    {
                        $statVisitStatDate = $v['schedule_updated_at'];
                    }
                }
            }
            else
            {
                $whatToDo = 'insert';
            }

            // 当前一周范围内已经存在的社区中心数据
            $stationIdArr   = self::getStationData($weekStartDate); // 此周内已经存在的工作站，用于稍后计算哪个社区中心既没有排班也没有出勤
            if (($weekStartDay >= 19) && ($weekStartDay <= 25))     // 跨月周
            {
                // 前半周数据对比和计算
                $halfWeekData = self::getData($weekStartDate, $monthEndDate);
                if ($halfWeekData)
                {
                    // 数据判断、数据处理
                    $nextMonthStationIdArr     = [];    // 下半周应出勤1天的社区中心
                    $halfNextMonthStationIdArr = [];    // 下半周应出勤0.5天的社区中心
                    foreach ($halfWeekData as $k => $v)
                    {
                        if (isset($stationIdArr[$v['station_id']]))
                        {
                            $halfNextMonthStationIdArr[$v['station_id']] = $stationIdArr[$v['station_id']];
                            unset($stationIdArr[$v['station_id']]);
                        }
                    }
                    $nextMonthStationIdArr = $stationIdArr;

                    // 前半周数据处理 ========================================== start
                    $data = $halfWeekData;

                    // 数据判断、数据处理
                    $newData = [];
                    foreach ($data as $k => $v)
                    {
                        $newData[$v['station_id']][] = $v;
                    }

                    $insertData = [];
                    foreach ($newData as $key => $value)
                    {
                        // 获取当前月数据的week_index值
                        $weekIndex = self::getWeekIndex($key, $visitMonth);

                        if (isset($stationIdArr[$key]))
                        {
                            unset($stationIdArr[$key]);     // 去除已经计算考勤的社区中心，用于稍后计算哪个社区中心既没有排班也没有出勤
                        }
                        $oneData = [];
                        $oneData['visit_month']         = $visitMonth;
                        $oneData['week_start_date']     = $weekStartDate;
                        $oneData['week_end_date']       = $weekEndDate;
                        $oneData['week_index']          = $weekIndex;
                        $oneData['station_id']          = $key;
                        $oneData['day_count_schedule']  = 10;// 为了对比计算，扩大10倍，保持整型数据
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 0;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $firstData['updated_at'];
                        foreach ($value as $k => $v)
                        {
                            // 实际出勤数
                            if (($v['status'] == 1) && ($v['visit_work_date'] >= $weekStartDate) && ($v['visit_work_date'] <= $weekEndDate))
                            {
                                switch ($v['visit_work_time'])
                                {
                                    case 1:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;    // 为了对比计算，扩大10倍
                                        break;
                                    case 2:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                        break;
                                    case 3:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 10;
                                        break;
                                    default:
                                        # do nothing...
                                        break;
                                }
                            }
                            // 患者数
                            $oneData['patient_count']   = $oneData['patient_count'] + $v['visit_patient_count'];
                            // 处方数
                            $oneData['recipe_count']    = $oneData['recipe_count'] + $v['visit_recipe_count'];
                            // 治未病数
                            $oneData['zhiweibing_count']= $oneData['zhiweibing_count'] + $v['visit_zhiweibing_count'];
                            // 原始数据更新日期
                            if ($oneData['schedule_updated_at'] < $v['updated_at'])
                            {
                                $oneData['schedule_updated_at'] = $v['updated_at'];
                            }
                        }
                        if ($scheduleUpdatedAt < $oneData['schedule_updated_at'])
                        {
                            $scheduleUpdatedAt = $oneData['schedule_updated_at'];
                        }

                        if ($oneData['day_count_schedule'] >= $oneData['day_count_visit'])
                        {
                            $oneData['day_count_schedule'] = $oneData['day_count_visit'];
                        }
                        else
                        {
                            unset($halfNextMonthStationIdArr[$key]);
                        }
                        // 应出勤、实际出勤、缺勤恢复正常值
                        $oneData['day_count_schedule'] = $oneData['day_count_schedule'] / 10;
                        $oneData['day_count_visit']    = $oneData['day_count_visit']    / 10;
                        $oneData['day_count_absent']   = $oneData['day_count_absent']   / 10;

                        $insertData[] = $oneData;

                    }   // end of foreach ($newData as $key => $value)

                    // 整体数据存储
                    if ($whatToDo == 'update')
                    {
                        if ($statVisitStatDate < $scheduleUpdatedAt)
                        {
                            // echo 1;
                            // $r = self::updateData($insertData);
                            // dd($r);
                            // echo $testNum;
                            // echo __LINE__;
                            // echo '<br>';
                            // echo '219---update---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周';
                            // echo '<hr>';
                            // echo '<hr>';
                            // echo '<hr>';
                            // $testNum++;
                            self::updateData($insertData);
                            // return self::updateData($insertData);
                        }
                        else
                        {
                            // echo $testNum;
                            // echo __LINE__;
                            // echo '<br>';
                            // echo '232---true---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周';
                            // echo '<hr>';
                            // echo '<hr>';
                            // $testNum++;
                            // return true;
                        }
                    }
                    else
                    {
                        // echo 2;
                        // $r = self::insertData($insertData);
                        // dd($r);
                            // echo $testNum;
                            // echo __LINE__;
                            // echo '<br>';
                            // echo '247---insert---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周';
                            // echo '<hr>';
                            // echo '<hr>';
                            // echo '<hr>';
                            // $testNum++;

                        self::updateData($insertData);
                        // self::insertData($insertData);
                        // return self::insertData($insertData);
                    }
                    // 前半周数据处理 ========================================== end

                    // 后半周数据处理 ========================================== start
                    $statVisitStatDate = DateHelper::now(); // 统计表里这一周“原始数据更新日期”最小的数据的“原始数据更新日期”
                    $scheduleUpdatedAt = '';                // 新统计数据里这一周的数据中的“更新时间”
                    $whatToDo = 'update';
                    if ($statVisitStationData)
                    {
                        foreach ($statVisitStationData as $v)
                        {
                            if ($statVisitStatDate > $v['schedule_updated_at'])
                            {
                                $statVisitStatDate = $v['schedule_updated_at'];
                            }
                        }
                    }
                    else
                    {
                        $whatToDo = 'insert';
                    }

                    // 后半周数据查询
                    $monthEndDate26   = date('Y-m', strtotime($weekStartDate));
                    $monthEndDate26   = $monthEndDate26.'-26';
                    // 前半周数据对比和计算
                    $data = self::getData($monthEndDate26, $weekEndDate);

                    // 数据判断、数据处理
                    $newData = [];
                    foreach ($data as $k => $v)
                    {
                        $newData[$v['station_id']][] = $v;
                    }

                    $insertData = [];
                    // $nextMonthStationIdArr       // 下半周应出勤1天的社区中心id数组
                    // $halfNextMonthStationIdArr   // 下半周应出勤0.5天的社区中心id数组
                    foreach ($newData as $key => $value)
                    {
                        // 获取当前月数据的week_index值
                        $weekIndex = 1;

                        $oneData = [];
                        $oneData['visit_month']     = $nextVisitMonth;
                        $oneData['week_start_date'] = $weekStartDate;
                        $oneData['week_end_date']   = $weekEndDate;
                        $oneData['week_index']      = $weekIndex;
                        $oneData['station_id']      = $key;
                        if (isset($halfNextMonthStationIdArr[$key]))
                        {
                            $oneData['day_count_schedule'] = 5;         // 为了对比计算，扩大10倍，保持整型
                            unset($halfNextMonthStationIdArr[$key]);    // 此社区中心已经被计算
                        }
                        elseif (isset($nextMonthStationIdArr[$key]))
                        {
                            $oneData['day_count_schedule'] = 10;
                            unset($nextMonthStationIdArr[$key]);        // 此社区中心已经被计算
                        }
                        else
                        {
                            $oneData['day_count_schedule'] = 0;
                        }
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 0;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $firstData['updated_at'];
                        foreach ($value as $k => $v)
                        {
                            // 实际出勤数
                            if (($v['status'] == 1) && ($v['visit_work_date'] >= $weekStartDate) && ($v['visit_work_date'] <= $weekEndDate))
                            {
                                switch ($v['visit_work_time'])
                                {
                                    case 1:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                        break;
                                    case 2:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                        break;
                                    case 3:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 10;
                                        break;
                                    default:
                                        # do nothing...
                                        break;
                                }
                            }
                            // 患者数
                            $oneData['patient_count']           = $oneData['patient_count'] + $v['visit_patient_count'];
                            // 处方数
                            $oneData['recipe_count']            = $oneData['recipe_count'] + $v['visit_recipe_count'];
                            // 治未病数
                            $oneData['zhiweibing_count']        = $oneData['zhiweibing_count'] + $v['visit_zhiweibing_count'];
                            // 原始数据更新日期
                            if ($oneData['schedule_updated_at'] < $v['updated_at'])
                            {
                                $oneData['schedule_updated_at'] = $v['updated_at'];
                            }
                        }
                        if ($scheduleUpdatedAt < $oneData['schedule_updated_at'])
                        {
                            $scheduleUpdatedAt = $oneData['schedule_updated_at'];
                        }

                        if ($oneData['day_count_schedule'] >= $oneData['day_count_visit'])
                        {
                            $oneData['day_count_absent']   = $oneData['day_count_schedule'] - $oneData['day_count_visit'];
                        }

                        // 应出勤、实际出勤、缺勤恢复正常值
                        $oneData['day_count_schedule'] = $oneData['day_count_schedule'] / 10;
                        $oneData['day_count_visit']    = $oneData['day_count_visit']    / 10;
                        $oneData['day_count_absent']   = $oneData['day_count_absent']   / 10;

                        $insertData[] = $oneData;

                    }   // end of foreach ($newData as $key => $value)

                    // 周缺勤社区中心数据处理
                    foreach ($nextMonthStationIdArr as $k => $v)
                    {
                        $oneData = [];
                        $oneData['visit_month']         = $nextVisitMonth;
                        $oneData['week_start_date']     = $weekStartDate;
                        $oneData['week_end_date']       = $weekEndDate;
                        $oneData['week_index']          = 1;
                        $oneData['station_id']          = $v;
                        $oneData['day_count_schedule']  = 1;
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 1;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $scheduleUpdatedAt;

                        $insertData[] = $oneData;
                    }   // end of foreach ($nextMonthStationIdArr as $k => $v)
                    foreach ($halfNextMonthStationIdArr as $k => $v)
                    {
                        $oneData = [];
                        $oneData['visit_month']         = $nextVisitMonth;
                        $oneData['week_start_date']     = $weekStartDate;
                        $oneData['week_end_date']       = $weekEndDate;
                        $oneData['week_index']          = 1;
                        $oneData['station_id']          = $v;
                        $oneData['day_count_schedule']  = 0.5;
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 0.5;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $scheduleUpdatedAt;

                        $insertData[] = $oneData;
                    }   // end of foreach ($halfNextMonthStationIdArr as $k => $v)

                    // 整体数据存储
                    if ($whatToDo == 'update')
                    {
                        if ($statVisitStatDate < $scheduleUpdatedAt)
                        {
                            self::updateData($insertData);
                        }
                        else
                        {

                        }
                    }
                    else
                    {
                        self::updateData($insertData);
                    }

                    // 后半周数据处理 ========================================== end

                }
                else
                {
                    // 此周考勤记录到下个月
                    $data = self::getData($weekStartDate, $weekEndDate);
                    if ($data)
                    {
                        // 数据判断、数据处理
                        $newData = [];
                        foreach ($data as $k => $v)
                        {
                            $newData[$v['station_id']][] = $v;
                        }

                        $nowDate    = DateHelper::now();
                        $insertData = [];
                        foreach ($newData as $key => $value)
                        {
                            if (isset($stationIdArr[$key]))
                            {
                                unset($stationIdArr[$key]); // 去除已经计算考勤的社区中心，用于稍后计算哪个社区中心既没有排班也没有出勤
                            }
                            $oneData = [];
                            $oneData['visit_month']         = $nextVisitMonth;
                            $oneData['week_start_date']     = $weekStartDate;
                            $oneData['week_end_date']       = $weekEndDate;
                            $oneData['week_index']          = 1;
                            $oneData['station_id']          = $key;
                            $oneData['day_count_schedule']  = 10;
                            $oneData['day_count_visit']     = 0;
                            $oneData['day_count_absent']    = 0;
                            $oneData['patient_count']       = 0;
                            $oneData['recipe_count']        = 0;
                            $oneData['zhiweibing_count']    = 0;
                            $oneData['created_at']          = $nowDate;
                            $oneData['updated_at']          = $nowDate;
                            $oneData['schedule_updated_at'] = $firstData['updated_at'];
                            foreach ($value as $k => $v)
                            {
                                // 实际出勤数
                                if (($v['status'] == 1) && ($v['visit_work_date'] >= $weekStartDate) && ($v['visit_work_date'] <= $weekEndDate))
                                {
                                    switch ($v['visit_work_time'])
                                    {
                                        case 1:
                                            $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                            break;
                                        case 2:
                                            $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                            break;
                                        case 3:
                                            $oneData['day_count_visit'] = $oneData['day_count_visit'] + 10;
                                            break;
                                        default:
                                            # do nothing...
                                            break;
                                    }
                                }
                                // 患者数
                                $oneData['patient_count'] = $oneData['patient_count'] + $v['visit_patient_count'];
                                // 处方数
                                $oneData['recipe_count'] = $oneData['recipe_count'] + $v['visit_recipe_count'];
                                // 治未病数
                                $oneData['zhiweibing_count'] = $oneData['zhiweibing_count'] + $v['visit_zhiweibing_count'];
                                if ($oneData['schedule_updated_at'] < $v['updated_at'])
                                {
                                    $oneData['schedule_updated_at'] = $v['updated_at'];
                                }
                            }
                            if ($scheduleUpdatedAt < $oneData['schedule_updated_at'])
                            {
                                $scheduleUpdatedAt = $oneData['schedule_updated_at'];
                            }

                            if ($oneData['day_count_schedule'] > $oneData['day_count_visit'])
                            {
                                $oneData['day_count_absent'] = $oneData['day_count_schedule'] - $oneData['day_count_visit'];
                            }

                            // 应出勤、实际出勤、缺勤恢复正常值
                            $oneData['day_count_schedule'] = $oneData['day_count_schedule'] / 10;
                            $oneData['day_count_visit']    = $oneData['day_count_visit']    / 10;
                            $oneData['day_count_absent']   = $oneData['day_count_absent']   / 10;

                            $insertData[] = $oneData;

                        }   // end of foreach ($newData as $key => $value)

                        // 计算没有排班也没有出勤的社区中心
                        foreach ($stationIdArr as $k => $v)
                        {
                            $oneData = [];
                            $oneData['visit_month']         = $nextVisitMonth;
                            $oneData['week_start_date']     = $weekStartDate;
                            $oneData['week_end_date']       = $weekEndDate;
                            $oneData['week_index']          = 1;
                            $oneData['station_id']          = $v;
                            $oneData['day_count_schedule']  = 1;
                            $oneData['day_count_visit']     = 0;
                            $oneData['day_count_absent']    = 1;
                            $oneData['patient_count']       = 0;
                            $oneData['recipe_count']        = 0;
                            $oneData['zhiweibing_count']    = 0;
                            $oneData['created_at']          = $nowDate;
                            $oneData['updated_at']          = $nowDate;
                            $oneData['schedule_updated_at'] = $firstData['updated_at']; // 以查询的第一条数据日期作为默认数据
                            $insertData[] = $oneData;
                        }   // end of foreach ($stationIdArr as $k => $v)

                        // 整体数据存储
                        if ($whatToDo == 'update')
                        {
                            if ($statVisitStatDate < $scheduleUpdatedAt)
                            {
                                // echo 1;
                                // $r = self::updateData($insertData);
                                // dd($r);
                                    // echo $testNum;
                                    // echo __LINE__;
                                    // echo '<br>';
                                    // echo '589---update---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周无数据';
                                    // echo '<hr>';
                                    // echo '<hr>';
                                    // echo '<hr>';
                                    // $testNum++;
                                self::updateData($insertData);
                                // return self::updateData($insertData);
                            }
                            else
                            {
                                // echo $testNum;
                                // echo __LINE__;
                                // echo '<br>';
                                // echo '601---true---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周无数据';
                                // echo '<hr>';
                                // echo '<hr>';
                                // $testNum++;
                                // return true;
                            }
                        }
                        else
                        {
                                // echo 2;
                                // $r = self::insertData($insertData);
                                // dd($r);
                                // echo $testNum;
                                // echo __LINE__;
                                // echo '<br>';
                                // echo '617---insert---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周无数据';
                                // echo '<hr>';
                                // echo '<hr>';
                                // echo '<hr>';
                                // $testNum++;

                            self::updateData($insertData);
                            // self::insertData($insertData);
                            // return self::insertData($insertData);
                        }
                    }
                    else
                    {
                        // 计算没有排班也没有出勤的社区中心
                        $insertData = [];
                        foreach ($stationIdArr as $k => $v)
                        {
                            $oneData = [];
                            $oneData['visit_month']         = $nextVisitMonth;
                            $oneData['week_start_date']     = $weekStartDate;
                            $oneData['week_end_date']       = $weekEndDate;
                            $oneData['week_index']          = 1;
                            $oneData['station_id']          = $v;
                            $oneData['day_count_schedule']  = 1;
                            $oneData['day_count_visit']     = 0;
                            $oneData['day_count_absent']    = 1;
                            $oneData['patient_count']       = 0;
                            $oneData['recipe_count']        = 0;
                            $oneData['zhiweibing_count']    = 0;
                            $oneData['created_at']          = $nowDate;
                            $oneData['updated_at']          = $nowDate;
                            $oneData['schedule_updated_at'] = $firstData['updated_at']; // 以查询的第一条数据日期作为默认数据
                            $insertData[] = $oneData;
                        }   // end of foreach ($stationIdArr as $k => $v)

                        // 整体数据存储
                                // echo $testNum;
                                // echo __LINE__;
                                // echo '<br>';
                                // echo '654---insert---if (($weekStartDay >= 19) && ($weekStartDay <= 25))跨越周前半周无数据';
                                // echo '<hr>';
                                // echo '<hr>';
                                // echo '<hr>';
                                // $testNum++;

                        self::updateData($insertData);
                        // self::insertData($insertData);
                        // return self::insertData($insertData);

                    }   // end of if ($data)

                }   // end of if ($halfWeekData)
            }
            else
            {
                // 计算当前所属月份
                $theVisitMonth = $visitMonth;
                if ($weekStartDay > 25)
                {
                    $theVisitMonth = $nextVisitMonth;
                }
                // 数据查询和处理
                $data = self::getData($weekStartDate, $weekEndDate);
                if ($data)
                {
                    // 数据判断、数据处理
                    $newData = [];
                    foreach ($data as $k => $v)
                    {
                        $newData[$v['station_id']][] = $v;
                    }

                    $nowDate    = DateHelper::now();
                    $insertData = [];
                    foreach ($newData as $key => $value)
                    {
                        if (isset($stationIdArr[$key]))
                        {
                            unset($stationIdArr[$key]); // 去除已经计算考勤的社区中心，用于稍后计算哪个社区中心既没有排班也没有出勤
                        }
                        // 获取当前月数据的week_index值
                        $weekIndex = self::getWeekIndex($k, $theVisitMonth);
                        $oneData = [];
                        $oneData['visit_month']         = $theVisitMonth;
                        $oneData['week_start_date']     = $weekStartDate;
                        $oneData['week_end_date']       = $weekEndDate;
                        $oneData['week_index']          = $weekIndex;
                        $oneData['station_id']          = $key;
                        $oneData['day_count_schedule']  = 10;
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 0;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $firstData['updated_at'];
                        foreach ($value as $k => $v)
                        {
                            // 实际出勤数
                            if (($v['status'] == 1) && ($v['visit_work_date'] >= $weekStartDate) && ($v['visit_work_date'] <= $weekEndDate))
                            {
                                switch ($v['visit_work_time'])
                                {
                                    case 1:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                        break;
                                    case 2:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 5;
                                        break;
                                    case 3:
                                        $oneData['day_count_visit'] = $oneData['day_count_visit'] + 10;
                                        break;
                                    default:
                                        # do nothing...
                                        break;
                                }
                            }
                            // 患者数
                            $oneData['patient_count'] = $oneData['patient_count'] + $v['visit_patient_count'];
                            // 处方数
                            $oneData['recipe_count']  = $oneData['recipe_count'] + $v['visit_recipe_count'];
                            // 治未病数
                            $oneData['zhiweibing_count'] = $oneData['zhiweibing_count'] + $v['visit_zhiweibing_count'];
                            if ($oneData['schedule_updated_at'] < $v['updated_at'])
                            {
                                $oneData['schedule_updated_at'] = $v['updated_at'];
                            }
                        }
                        if ($scheduleUpdatedAt < $oneData['schedule_updated_at'])
                        {
                            $scheduleUpdatedAt = $oneData['schedule_updated_at'];
                        }

                        if ($oneData['day_count_schedule'] > $oneData['day_count_visit'])
                        {
                            $oneData['day_count_absent']   = $oneData['day_count_schedule'] - $oneData['day_count_visit'];
                        }

                        // 应出勤、实际出勤、缺勤恢复正常值
                        $oneData['day_count_schedule'] = $oneData['day_count_schedule'] / 10;
                        $oneData['day_count_visit']    = $oneData['day_count_visit']    / 10;
                        $oneData['day_count_absent']   = $oneData['day_count_absent']   / 10;

                        $insertData[] = $oneData;

                    }   // end of foreach ($newData as $key => $value)

                    // 计算没有排班也没有出勤的社区中心
                    foreach ($stationIdArr as $k => $v)
                    {
                        // 获取当前月数据的week_index值
                        $weekIndex = self::getWeekIndex($k, $theVisitMonth);
                        $oneData = [];
                        $oneData['visit_month']         = $theVisitMonth;
                        $oneData['week_start_date']     = $weekStartDate;
                        $oneData['week_end_date']       = $weekEndDate;
                        $oneData['week_index']          = $weekIndex;
                        $oneData['station_id']          = $v;
                        $oneData['day_count_schedule']  = 1;
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 1;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $firstData['updated_at']; // 以查询的第一条数据日期作为默认数据
                        $insertData[] = $oneData;
                    }   // end of foreach ($stationIdArr as $k => $v)

                    // 整体数据存储
                    if ($whatToDo == 'update')
                    {
                        if ($statVisitStatDate < $scheduleUpdatedAt)
                        {
                            self::updateData($insertData);exit;
                        }
                        else
                        {

                        }
                    }
                    else
                    {
                        self::updateData($insertData);
                    }
                }
                else
                {
                    // 计算没有排班也没有出勤的社区中心的统计数据
                    $insertData = [];
                    foreach ($stationIdArr as $k => $v)
                    {
                        // 获取当前月数据的week_index值
                        $weekIndex = self::getWeekIndex($k, $theVisitMonth);
                        $oneData = [];
                        $oneData['visit_month']         = $theVisitMonth;
                        $oneData['week_start_date']     = $weekStartDate;
                        $oneData['week_end_date']       = $weekEndDate;
                        $oneData['week_index']          = $weekIndex;
                        $oneData['station_id']          = $v;
                        $oneData['day_count_schedule']  = 1;
                        $oneData['day_count_visit']     = 0;
                        $oneData['day_count_absent']    = 1;
                        $oneData['patient_count']       = 0;
                        $oneData['recipe_count']        = 0;
                        $oneData['zhiweibing_count']    = 0;
                        $oneData['created_at']          = $nowDate;
                        $oneData['updated_at']          = $nowDate;
                        $oneData['schedule_updated_at'] = $firstData['updated_at']; // 以查询的第一条数据日期作为默认数据
                        $insertData[] = $oneData;
                    }   // end of foreach ($stationIdArr as $k => $v)

                    // 整体数据存储

                    self::updateData($insertData);


                }   // end of if ($data)
            }

            $whileNum++;    // 下一周
        }
        // 循环的对所有数据进行处理 ====================================================== end
    }

    // 社区服务站数据查询
    private static function getStationData($startDate = '')
    {
        $data = [];
        if ($startDate)
        {
            $data = MzyStation::where('created_at', '<=', $startDate)
                           ->select(['id'])
                           // ->take(5000)
                           ->get();
            if ($data)
            {
                $data = $data->toArray();
            }
            $idArr = [];
            foreach ($data as $v)
            {
                $idArr[$v['id']] = $v['id'];
            }
            $data  = $idArr;
        }
        // else
        // {
            // 获取全部社区服务站
            // $data = MzyStation::get();
            // if ($data)
            // {
            //     $data = $data->toArray();
            // }
        // }
        return $data;
    }

    // 排班出勤数据查询
    private static function getData($startDate = '', $endDate = '')
    {
        $data = [];
        if ($startDate && $endDate)
        {
            $data = MzyDoctorSchedule::whereBetween('work_date', [$startDate, $endDate])
                  ->orderBy('work_date','ASC')
                  // ->select(['id', 'station_id', 'work_date', 'work_time', 'status', 'visit_work_date', 'visit_work_time', 'visit_patient_count', 'visit_recipe_count', 'visit_zhiweibing_count', 'created_at', 'updated_at'])
                  // ->take(5000)  // 设置一个默认的上限
                  ->get();
            if ($data)
            {
                $data = $data->toArray();
            }
        }
        return $data;
    }

    // 统计数据查询
    private static function getStatVisitStationData($startDate = '', $endDate = '')
    {
        $data = [];
        if ($startDate && $endDate)
        {
            $data = MzyStatVisitStation::where('week_start_date', $startDate)
                  ->where('week_end_date', $endDate)
                  ->orderBy('id','ASC')
                  // ->take(5000)  // 设置一个默认的上限
                  ->get();
            if ($data)
            {
                $data = $data->toArray();
            }
        }
        return $data;
    }

    // 统计数据存储
    private static function insertData($data = [])
    {
        if ($data)
        {
            return MzyStatVisitStation::insert($data);
        }
        return null;
    }

    // 统计数据更新
    private static function updateData($data = [])
    {
        $res = true;
        $check = true;
        if ($data)
        {
            $newData = [];
            foreach ($data as $v)
            {
                $theData = MzyStatVisitStation::where('station_id', $v['station_id'])
                         ->where('week_start_date', $v['week_start_date'])
                         ->where('week_end_date', $v['week_end_date'])
                         ->first();
                if ($theData)
                {
                    if (isset($v['created_at']))
                    {
                        unset($v['created_at']);
                    }
                    $check = MzyStatVisitStation::where('id',$theData->id)->update($v);
                    if (($res == true) && (!$check))
                    {
                        $res == false;
                    }
                    // usleep(1000);   // 防止对mysql数据库操作过快
                }
                else
                {
                    $newData[] = $v;
                }
            }
            if ($newData)
            {
                $check = MzyStatVisitStation::insert($newData);
                if (($res == true) && (!$check))
                {
                    $res == false;
                }
            }
        }
        return $res;    // $res == true, 数据全部添加、编辑成功；$res == false,部分数据添加、编辑失败。
    }

    // 获取当前月数据的week_index值
    private static function getWeekIndex($stationId, $visitMonth)
    {
        $weekIndex = 1;
        $weekIndexData = MzyStatVisitStation::where('station_id', $stationId)
                      ->where('visit_month', $visitMonth)
                      ->orderBy('week_index','DESC')
                      ->first();
        if ($weekIndexData)
        {
            $weekIndex = $weekIndexData->week_index + 1;
        }
        return $weekIndex;
    }

}
